import { DIST } from "@/constant";
import { get } from "@/utils/http/httpUtil";

// 定义 state
const state = {
    value: {}, // {type:[]}  数组形式
    object: {}, // 对象形式
    isInit: true
};

// 定义 getters
const getters = {
    val: (state) => (code) => {
        return state.value[code];
    },
    obj: (state) => (code) => {
        return state.object[code];
    },
    default: (state) => async (code) => {
        if (state.value[code]) {
            for (let o of state.value[code]) {
                if (o.isDefault === 1) {
                    return String(o.value);
                }
            }
        }
    }
};

// 定义 mutations
const mutations = {
    // 更新 state 中的 value
    SET_VALUE(state, value) {
        state.value = value;
    },
    // 更新 state 中的 object
    SET_OBJECT(state, object) {
        state.object = object;
    },
    // 更新 state 中的 isInit
    SET_IS_INIT(state, isInit) {
        state.isInit = isInit;
    }
};

// 定义 actions
const actions = {
    async init({ dispatch, state }, http) {
        if (state.isInit) {
            await dispatch('initValue', http);
        }
    },
    async initValue({ commit, dispatch }, http) {
        commit('SET_IS_INIT', false);
        let dictItems = localStorage.getItem(DIST);
        if (dictItems) {
            let value = JSON.parse(dictItems);
            commit('SET_VALUE', value);
            let obj = {};
            for (let key of Object.keys(value)) {
                for (let o of value[key]) {
                    o.label = o.dictLabel;
                    o.value = String(o.dictValue);
                    obj[o.dictCode] = o;
                }
            }
            commit('SET_OBJECT', obj);
        } else {
            await dispatch('refresh', http);
        }
    },
    async refresh({ commit }, http) {
        await get( '/online/sysDictData/listOnline').then((value) => {
            let obj = {};
            for (let key of Object.keys(value)) {
                for (let o of value[key]) {
                    o.label = o.dictLabel;
                    o.value = String(o.dictValue);
                    obj[o.dictCode] = o;
                }
            }
            commit('SET_VALUE', value);
            commit('SET_OBJECT', obj);
            localStorage.setItem(DIST, JSON.stringify(value));
        });
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
};
